package br.com.iswe.recipemaster.dao.security;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import br.com.iswe.recipemaster.entities.security.User;

public class UserDetailsDAOImpl implements UserDetailsService {

	protected static final Log log = LogFactory.getLog(UserDetailsDAOImpl.class);

	private UserDAO userDAO;
	
	public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException, DataAccessException {
		//
		User user = new User();
		user.setEmail(email);
		List<User> lista = userDAO.getObjects(user);
		if(lista == null || lista.size() == 0){
			throw new UsernameNotFoundException("Email: '" + email + "' not found.");
		}
		return createDetails( lista.get(0) );
	}

	private UserDetails createDetails(User user) {
		UserDetailsImpl obj = new UserDetailsImpl(user);
		obj.setUserDAO(userDAO);
		return obj;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
}
